package cn.cupk.logsystem.service.serviceImpl;

import cn.cupk.logsystem.log.observerPattern.Logger;
import cn.cupk.logsystem.log.singletonpattern.LogManager;
import cn.cupk.logsystem.pojo.User;
import cn.cupk.logsystem.mapper.*;
import cn.cupk.logsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOGGER = LogManager.getInstance().getLogger(UserServiceImpl.class.getName());

    @Autowired
    private UserMapper userMapper;

    @Override
    public void createUser(User user) {
        userMapper.insertUser(user);
        LOGGER.info("Created user: " + user);
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectUserById(id);
        if (user != null) {
            LOGGER.info("Retrieved user: " + user);
        } else {
            LOGGER.warning("User not found with id: " + id);
        }
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.selectAllUsers();
        if (!users.isEmpty()) {
            LOGGER.info("Retrieved all users: " + users);
        } else {
            LOGGER.warning("No users found");
        }
        return users;
    }

    @Override
    public void updateUser(User user) {
        try {
            userMapper.updateUser(user);
            LOGGER.info("Updated user: " + user);
        } catch (Exception e) {
            LOGGER.severe("Failed to update user: " + user + " - " + e.getMessage());
        }
    }

    @Override
    public void deleteUser(Long id) {
        try {
            userMapper.deleteUser(id);
            LOGGER.info("Deleted user with id: " + id);
        } catch (Exception e) {
            LOGGER.severe("Failed to delete user with id: " + id + " - " + e.getMessage());
        }
    }
}
